package com.xyazm.inventory.processor;

import com.xyazm.common.redis.RedisCache;
import com.xyazm.inventory.cache.CacheSupport;
import com.xyazm.inventory.dao.ProductStockDAO;
import com.xyazm.inventory.domain.entity.ProductStockDO;
import com.xyazm.inventory.domain.param.AddProductStockParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 添加商品库存处理器
 * @author xuyou
 * @date 2022年07月30日 15:21
 */
@Slf4j
@Component
public class AddProductStockProcessor {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ProductStockDAO productStockDAO;


    /**
     * 执行添加商品库存逻辑
     * @author xuyou
     * 2022/8/6 0006 23:04
     * @param param
    */
    @Transactional(rollbackFor = Exception.class)
    public void doAdd(AddProductStockParam param) {
        // 1、构造商品库存
        ProductStockDO productStock = buildProductStock(param);
        // 2、保存商品库存到mysql
        productStockDAO.save(productStock);
        // 3、保存商品库存到redis
        addStockToRedis(productStock);
    }

    /**
     * 构造商品库存
     * @author xuyou
     * 2022/8/6 0006 23:05
     * @param param
     * @return com.xyazm.inventory.domain.entity.ProductStock
    */
    private ProductStockDO buildProductStock(AddProductStockParam param) {
        ProductStockDO productStock = new ProductStockDO();
        productStock.setSkuCode(param.getSkuCode());
        productStock.setSaleStockQuantity(param.getSaleStockQuantity());
        productStock.setSaledStockQuantity(0L);
        return productStock;
    }


    /**
     * 保存商品库存到redis
     * @param productStock
     */
    public void addStockToRedis(ProductStockDO productStock) {
        String productStockKey = CacheSupport.buildProductStockKey(productStock.getSkuCode());
        Map<String,String> productStockValue = CacheSupport
                .buildProductStockValue(productStock.getSaleStockQuantity(),productStock.getSaledStockQuantity());
        redisCache.hPutAll(productStockKey,productStockValue);
    }

}
